#!/bin/bash

set -o errexit

download(){
  # wget安装
  if [[ ! `which wget` ]]; then
    if check_sys sysRelease ubuntu;then
        apt-get install -y wget
    elif check_sys sysRelease centos;then
        yum install -y wget
    fi 
  fi

  local url1=$1
  local url2=$2
  local filename=$3
  
  speed1=`curl -m 5 -L -s -w '%{speed_download}' "$url1" -o /dev/null || true`
  speed1=${speed1%%.*}
  speed2=`curl -m 5 -L -s -w '%{speed_download}' "$url2" -o /dev/null || true`
  speed2=${speed2%%.*}
  echo "speed1:"$speed1
  echo "speed2:"$speed2
  url=$url1
  if [[ $speed2 -gt $speed1 ]]; then
    url=$url2
  fi
  echo "using url:"$url
  wget "$url" -O $filename

}

#判断系统版本
check_sys(){
    local checkType=$1
    local value=$2

    local release=''
    local systemPackage=''
    local packageSupport=''

    if [[ "$release" == "" ]] || [[ "$systemPackage" == "" ]] || [[ "$packageSupport" == "" ]];then

        if [[ -f /etc/redhat-release ]];then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "debian";then
            release="debian"
            systemPackage="apt"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "ubuntu";then
            release="ubuntu"
            systemPackage="apt"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat";then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "debian";then
            release="debian"
            systemPackage="apt"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "ubuntu";then
            release="ubuntu"
            systemPackage="apt"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "centos|red hat|redhat";then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        else
            release="other"
            systemPackage="other"
            packageSupport=false
        fi
    fi

    echo -e "release=$release\nsystemPackage=$systemPackage\npackageSupport=$packageSupport\n" > /tmp/ezhttp_sys_check_result

    if [[ $checkType == "sysRelease" ]]; then
        if [ "$value" == "$release" ];then
            return 0
        else
            return 1
        fi

    elif [[ $checkType == "packageManager" ]]; then
        if [ "$value" == "$systemPackage" ];then
            return 0
        else
            return 1
        fi

    elif [[ $checkType == "packageSupport" ]]; then
        if $packageSupport;then
            return 0
        else
            return 1
        fi
    fi
}

get_sys_ver() {
cat > /tmp/sys_ver.py <<EOF
import platform
import re

sys_ver = platform.platform()
sys_ver = re.sub(r'.*-with-(.*)-.*',"\g<1>",sys_ver)
if sys_ver.startswith("centos-7"):
    sys_ver = "centos-7"
if sys_ver.startswith("centos-6"):
    sys_ver = "centos-6"
print sys_ver
EOF
echo `python /tmp/sys_ver.py`
}

upgrade_db() {
eval `grep MYSQL_PASS /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_IP /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_PORT /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_DB /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_USER /opt/cdnfly/master/conf/config.py`


mysql -N -h$MYSQL_IP -u$MYSQL_USER -p$MYSQL_PASS -P$MYSQL_PORT $MYSQL_DB -e 'show processlist' | awk '{print $1}' | xargs kill || true
cd /opt/cdnfly/master/conf
supervisorctl stop cc_auto_switch site_res_count site_sync task node_monitor

cat > /tmp/_db.py <<'EOF'
# -*- coding: utf-8 -*-

import sys
sys.path.append("/opt/cdnfly/master/")
from model.db import Db
import pymysql
import json
reload(sys) 
sys.setdefaultencoding('utf8')

conn = Db()
try:
    # ocsp    
    if not conn.fetchone("select * from config where name='https_listen-ocsp_stapling' "):
        conn.execute("insert into config values ('https_listen-ocsp_stapling','1','site_default_config','0','global', now(),now(),1,null); ")
        conn.commit()

    # pending_node表
    if not conn.fetchone("SHOW TABLES LIKE 'pending_node'"):
        conn.execute("create table `pending_node` (`id` int(11) not null AUTO_INCREMENT,`ip` varchar(50),`create_at` datetime,KEY `idx_ip` (`ip`),primary KEY `id` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;")
        conn.commit()

    if conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_schema='cdn' and table_name = 'node' AND column_name = 'host';"):
        conn.execute("alter table node drop host")

    if conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_schema='cdn' and table_name = 'node' AND column_name = 'port';"):
        conn.execute("alter table node drop port")

    if conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_schema='cdn' and table_name = 'node' AND column_name = 'http_proxy';"):
        conn.execute("alter table node drop http_proxy")

    if conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_schema='cdn' and table_name = 'node' AND column_name = 'is_mgmt';"):
        conn.execute("alter table node drop is_mgmt")

    # 5000 9001 6379端口不再禁用
    config_value = conn.fetchone("select value from config where name='custom-port-not-allow' and type='site_stream' ")['value']
    pre_port = config_value.split()
    del_port = ['5000', '9001', '6379']
    done_port = " ".join(list(set(pre_port) - set(del_port)))
    conn.execute("update config set value=%s where name='custom-port-not-allow' and type='site_stream' ", done_port)
    conn.commit()


except:
    conn.rollback()
    raise

finally:
    conn.close()
EOF

/opt/venv/bin/python /tmp/_db.py

# 设置mysql隔离级别
if check_sys sysRelease ubuntu;then
    my_cnf_path="/etc/mysql/mariadb.conf.d/50-server.cnf"

elif check_sys sysRelease centos;then
    my_cnf_path="/etc/my.cnf"
    if [[ ! -f "$my_cnf_path" ]];then
        my_cnf_path="/etc/my.cnf.d/server.cnf"
    fi

fi    
if [[ "`grep transaction-isolation $my_cnf_path`" == "" ]];then
    sed -i '/\[mysqld\]/a\transaction-isolation = READ-COMMITTED' $my_cnf_path
fi

mysql -N -h$MYSQL_IP -u$MYSQL_USER -p$MYSQL_PASS -P$MYSQL_PORT $MYSQL_DB -e 'set global transaction isolation level READ COMMITTED'  || true

# 安装py依赖
cd /tmp
download "https://dl2.cdnfly.cn/cdnfly/pymodule-master-20230102.tar.gz" "https://us.centos.bz/cdnfly/pymodule-master-20230102.tar.gz" "pymodule-master-20230102.tar.gz"
tar xf pymodule-master-20230102.tar.gz
cd pymodule-master-20230102

/opt/venv/bin/pip install python_engineio-3.14.2-py2.py3-none-any.whl
/opt/venv/bin/pip install python_socketio-4.4.0-py2.py3-none-any.whl
/opt/venv/bin/pip install greenlet-2.0.1-cp27-cp27mu-manylinux2010_x86_64.whl
/opt/venv/bin/pip install gevent-22.10.2-cp27-cp27mu-manylinux2010_x86_64.whl 
/opt/venv/bin/pip install gevent-websocket-0.10.1.tar.gz
/opt/venv/bin/pip install websocket_client-0.59.0-py2.py3-none-any.whl 
/opt/venv/bin/pip install Flask_SocketIO-4.3.2-py2.py3-none-any.whl 
/opt/venv/bin/pip install simplejson-3.18.0-cp27-cp27mu-manylinux2010_x86_64.whl
sed -i 's/from json import JSONDecodeError/from simplejson import JSONDecodeError/' /opt/venv/lib/python2.7/site-packages/engineio/client.py

# 更新panel或conf
flist='master/panel/src/views/node/pending/
master/conf/nginx_global.tpl
master/conf/nginx_http_vhost.tpl
master/conf/supervisor_master.conf
master/panel/console/index.html
master/panel/src/views/config/default/index.html
master/panel/src/views/node/node/index.html
master/panel/src/views/node/node/nodeform.html
master/panel/src/views/system/update/index.html'

for f in `echo $flist`;do
\cp -a /opt/$dir_name/$f /opt/cdnfly/$f
done

}

update_file() {
cd /opt/$dir_name/master/
for i in `find ./ | grep -vE "^./$|^./agent$|^./conf$|conf/config.py|conf/nginx_global.tpl|conf/supervisor_master.conf|conf/nginx_http_default.tpl|conf/nginx_http_vhost.tpl|conf/nginx_stream_vhost.tpl|conf/ssl.cert|conf/ssl.key|^./panel"`;do
    \cp -aT $i /opt/cdnfly/master/$i
done

}

# 定义版本
version_name="v5.3.0"
version_num="50300"
dir_name="cdnfly-master-$version_name"
tar_gz_name="$dir_name-$(get_sys_ver).tar.gz"

# 下载安装包
cd /opt
echo "开始下载$tar_gz_name..."
download "https://dl2.cdnfly.cn/cdnfly/$tar_gz_name" "https://us.centos.bz/cdnfly/$tar_gz_name" "$tar_gz_name"
echo "下载完成"

echo "开始解压..."
rm -rf $dir_name
tar xf $tar_gz_name
echo "解压完成"

cd /opt
echo "准备升级数据库..."
upgrade_db
echo "升级数据库完成"

echo "更新文件..."
update_file
echo "更新文件完成."

echo "修改config.py版本..."
sed -i "s/VERSION_NAME=.*/VERSION_NAME=\"$version_name\"/" /opt/cdnfly/master/conf/config.py
sed -i "s/VERSION_NUM=.*/VERSION_NUM=\"$version_num\"/" /opt/cdnfly/master/conf/config.py
echo "修改完成"

echo "开始重启主控..."
#supervisorctl restart all
supervisorctl -s http://127.0.0.1:9001 reload || supervisorctl  -c /opt/cdnfly/master/conf/supervisord.conf reload
echo "重启完成"

echo "清理文件"
rm -rf /opt/$dir_name
rm -f /opt/$tar_gz_name
echo "清理完成"

echo "完成$version_name版本升级"